package com.briup.pts.service.impl;

import com.briup.pts.config.auth.TokenMapContext;
import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Account;
import com.briup.pts.domain.dto.UserLoginDTO;
import com.briup.pts.mapper.UserMapper;
import com.briup.pts.service.UserService;
import com.briup.pts.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    @Value("${auth.header-name}")
    private String headerName;

    @Override
    public Map<String, String> login(UserLoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 根据用户名获取用户信息
        Account account = userMapper.queryByUsername(username);
        if (account==null){
            throw new ServiceException(ResultCode.USER_IS_NOT_EXISTS);
        }
        // 校验密码
        if (!password.equals(account.getPassword())){
            throw new ServiceException(ResultCode.PASSWORD_IS_ERROR);
        }
        // 校验账户状态是否可用
        if (account.getStatus()==0){
            throw new ServiceException(ResultCode.ACCOUNT_IS_UNABLE);
        }
        // 在上述校验都通过的情况下，表示登录成功，生成token令牌
        String accountId = account.getAccountId();
        Map<String, Object> claims = Map.of("accountId", accountId);
        String token = JwtUtil.sign(claims);

        // 登录成功后，还应该将token放入到TokenMapContext中进行维护，
        // 以防在退出登录后还能通过为过期的token 获取到用户信息或使用系统
        TokenMapContext.put(accountId,token);

        // 返回token数据
        return Map.of(headerName,token);
    }

    @Override
    public Account queryById(String userId) {
        return userMapper.queryById(userId);
    }
}
